﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using lyAdmin.Common;
using lyAdmin.Common.Result;
using lyAdmin.Domain.Common;
using lyAdmin.Domain.IDomain;
using lyAdmin.Entity;
using lyAdmin.Entity.Enum;
using lyAdmin.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SshNet.Security.Cryptography;

namespace lyAdmin.Controllers.Admin
{
    [Area("Admin")]
    [Route("Admin/[controller]/[action]")]
    public class SystemController : BaseController
    {
        private IAdminService adminService = null;
        private IHttpContextAccessor _accessor;
        public SystemController(IAdminService adminService, IHttpContextAccessor accessor)
        {
            this.adminService = adminService;
            _accessor = accessor;
        }
        [ApiExplorerSettings(IgnoreApi = true)]
        public IActionResult Login()
        {
            ViewData["basePath"] = $"{this.Request.Scheme}://{this.Request.Host}/{this.Request.PathBase}";
            if (!string.IsNullOrEmpty(GetCookies("token")))
            {
                //更新缓存
                string token = GetCookies("token");
                lyAdmin.Entity.Admin admin = Redis.Get<lyAdmin.Entity.Admin>(token);
                DeleteCookies("token");
                if (admin != null)
                {
                    SetCookies("token", token, 86400*1000);
                    Redis.Del(admin.Token + "userInfo");
                    admin = adminService.Get(admin.Id);
                    Redis.Set(admin.Token + "userInfo", admin, 86400 * 1000);
                    return Redirect("main");
                }
            }
            return View();
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="login"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [ApiExplorerSettings(IgnoreApi = true)]
        public JsonResult SginIn(string login, string password)
        {
            ServiceResult res = adminService.SginIn(login, password, _accessor.HttpContext.Connection.RemoteIpAddress.ToString());
            if (!res.State)
            {
                return AjaxResultUtil.Fail(res.Msg);
            }
            lyAdmin.Entity.Admin admin = (lyAdmin.Entity.Admin)res.Data;

            SetCookies("token", admin.Token, 86400 * 1000);
            Redis.Set(admin.Token + "userInfo", admin, 86400 * 1000);

            return AjaxResultUtil.Success("admin/system/main");
        }
        [ApiExplorerSettings(IgnoreApi = true)]
        public IActionResult Main()
        {
            return View();
        }
        /// <summary>
        /// 获取枚举类型
        /// </summary>
        /// <returns></returns>
        [ApiExplorerSettings(IgnoreApi = true)]
        public JsonResult types()
        {

            Dictionary<string,object> lst = new Dictionary<string, object>();
            //反射遍历实体类内的枚举
            Type[] type = Assembly.Load("lyAdmin.Entity").GetTypes();
            for (int i = 0; i < type.Length; i++) {
                if (type[i].FullName.Contains("lyAdmin.Entity.Enum"))
                {
                    List<Dictionary<string, object>> enums = new List<Dictionary<string, object>>();
                    //遍历枚举选项
                    FieldInfo[] keys = type[i].GetFields();
                    for(int j = 0; j < keys.Length; j++)
                        if(keys[j].FieldType.IsEnum)
                        {
                            Dictionary<string, object> dic = new Dictionary<string, object>();
                            //获取注释
                            object[] attr = keys[j].GetCustomAttributes(typeof(DescriptionAttribute), false);  
                            string description = attr.Length == 0 ? keys[j].Name : ((DescriptionAttribute)attr[0]).Description;

                            string val = Enum.Format(type[i], Enum.Parse(type[i], keys[j].Name), "d"); 
                            dic.Add("code", int.Parse(val));
                            dic.Add("label", description.Split("|")[0]);
                            dic.Add("visible", Boolean.Parse(description.Split("|")[1]).ToString().ToLower());
                            enums.Add(dic);
                        }
                    lst.Add(type[i].FullName.Split(".").Last().ToString(), enums);
                }
            }
             
            return AjaxResultUtil.Success(lst);
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        [ApiExplorerSettings(IgnoreApi = true)]
        public JsonResult loginout()
        {
            string token = GetCookies("token");
            DeleteCookies("token");  
            Redis.Del(token + "userInfo");
            return AjaxResultUtil.Success();
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        [ApiExplorerSettings(IgnoreApi = true)]
        public JsonResult updatePassword(string password)
        {
            string token = GetCookies("token");
            lyAdmin.Entity.Admin admin = Redis.Get<lyAdmin.Entity.Admin>(token);
            ServiceResult res = adminService.UpdatePassword(admin, password);
            if (res.State)
                return AjaxResultUtil.Success();
            else
                return AjaxResultUtil.Fail();
        }
    }
}
